Majority Element
Question
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Analysis
直接Array排序后找最多会超时
Code
|
|
Majority Element II
Question
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Analysis
最多只可能有两个符合条件的元素,利用两个cnt和num记录
第一次遍历找到可能符合条件的num,再一次遍历确定是否超过n/3
Code
|
|